import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import os

matplotlib.use('Agg')
plt.rcParams['font.sans-serif'] = ['MiSans']
plt.rcParams['axes.unicode_minus'] = False

def analyze_csv_data(csv_file_path):
    if not os.path.exists(csv_file_path):
        print(f"文件不存在: {csv_file_path}")
        return
    
    try:
        df = pd.read_csv(csv_file_path, header=None, names=['request', 'timestamp'])
        df['datetime'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M:%S')
        df['date'] = df['datetime'].dt.date
        df['hour'] = df['datetime'].dt.hour
        # sns.set(style="whitegrid")
        plt.figure(figsize=(12, 6))
        date_counts = df['date'].value_counts().sort_index()
        ax = date_counts.plot(kind='bar', color='skyblue')
        
        # 计算日期请求的平均值并添加虚线
        date_mean = date_counts.mean()
        ax.axhline(y=date_mean, color='red', linestyle='--', label=f'平均值: {date_mean:.2f}')
        ax.legend()
        
        plt.title('按日期统计的请求数量', fontsize=16)
        plt.xlabel('日期', fontsize=14)
        plt.ylabel('请求数量', fontsize=14)
        date_labels = [d.strftime('%m-%d') for d in date_counts.index]
        plt.xticks(range(len(date_counts)), date_labels, rotation=45)
        plt.tight_layout()
        for i, v in enumerate(date_counts):
            ax.text(i, v + 0.1, str(v), ha='center', fontsize=10)
        plt.savefig('by_date.svg', format='svg')
        print(f"已保存日期统计图表到: {os.path.abspath('by_date.svg')}")
        
        plt.figure(figsize=(12, 6))
        hour_counts = df['hour'].value_counts().sort_index()
        all_hours = pd.Series(0, index=range(24))
        hour_counts = hour_counts.add(all_hours, fill_value=0)
        hour_counts = hour_counts.sort_index()
        
        ax = hour_counts.plot(kind='bar', color='lightgreen')
        
        # 计算小时请求的平均值并添加虚线
        hour_mean = hour_counts.mean()
        ax.axhline(y=hour_mean, color='red', linestyle='--', label=f'平均值: {hour_mean:.2f}')
        ax.legend()
        
        plt.title('24小时内各时间点的请求数量', fontsize=16)
        plt.xlabel('小时', fontsize=14)
        plt.ylabel('请求数量', fontsize=14)
        plt.xticks(range(24), [f"{h}~{h+1}" for h in range(24)], rotation=45)
        plt.tight_layout()
        for i, v in enumerate(hour_counts):
            ax.text(i, v + 0.1, str(int(v)), ha='center', fontsize=10)
        
        plt.savefig('by_hour.svg', format='svg')
        print(f"已保存小时统计图表到: {os.path.abspath('by_hour.svg')}")
        
        print("\n数据统计信息:")
        print(f"总请求数: {len(df)}")
        print(f"日期范围: {df['date'].min()} 至 {df['date'].max()}")
        print("\n请求最多的日期:")
        top_dates = date_counts.sort_values(ascending=False).head(5)
        for date, count in top_dates.items():
            print(f"  {date}: {count}次请求")

        # 新增超过平均值的日期统计
        print("\n超过平均请求的日期:")
        above_avg_dates = date_counts[date_counts > date_mean]
        if not above_avg_dates.empty:
            weekday_cn = ['日', '一', '二', '三', '四', '五', '六']
            dates_str = []
            for date in above_avg_dates.index:
                # 添加星期信息
                weekday_num = pd.Timestamp(date).strftime('%w')
                dates_str.append(f"{date.strftime('%Y-%m-%d')}（星期{weekday_cn[int(weekday_num)]}）")
            print("、".join(dates_str))
        else:
            print("无")

        print("\n请求最多的时间段:")
        top_hours = hour_counts.sort_values(ascending=False).head(5)
        for hour, count in top_hours.items():
            print(f"  {hour}:00-{hour+1}:00: {int(count)}次请求")

        # 新增超过平均值的时间段统计
        print("\n超过平均请求的时间段:")
        above_avg_hours = hour_counts[hour_counts > hour_mean]
        for hour, count in above_avg_hours.items():
            print(f"{hour}:00-{hour+1}:00",end="、")
        
    except Exception as e:
        print(f"处理CSV文件时发生错误: {e}")

def main():
    csv_file_path = "log.csv"
    
    analyze_csv_data(csv_file_path)

if __name__ == "__main__":
    main()